"""
Author: xiash$
Date: 2025/9/30$
Project: open-image$
Description: $
***
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
*  O\ = /O
* ___/`---'\____
* .   ' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
*          .............................................
*           佛曰：bug泛滥，我已瘫痪！
"""
from pathlib import Path
from typing import Any

import numpy as np
from osgeo import ogr, gdal


def safe_create_shp_field(ogr_layer: ogr.Layer, field_name: str, field_type: int):
    """
    安全的创建shp字段
    :param ogr_layer: ogr.Layer
    :param field_name: shp字段名称
    :param field_type: shp字段数据类型，如 ogr.OFTString
    :return:
    """
    # 检查字段是否已存在
    layer_defn = ogr_layer.GetLayerDefn()
    field_index = layer_defn.GetFieldIndex(field_name)
    if field_index >= 0 and layer_defn.GetFieldDefn(field_index).GetType() != field_type:
        # 先删除现有字段
        ret = ogr_layer.DeleteField(field_index)
        if ret != 0:
            raise ValueError(f"无法创建字段: {field_name}！")
    if field_index < 0 or layer_defn.GetFieldDefn(field_index).GetType() != field_type:
        # 创建新字段
        field_defn = ogr.FieldDefn(field_name, field_type)
        ogr_layer.CreateField(field_defn)


def read_image_data(raster_path: str, backend: str = "gdal") -> Any:
    """
    读取栅格数据
    :param raster_path: 栅格数据路径
    :param backend: 使用的后端库名称
    :return: gdal.Dataset
    """
    match backend:
        case "gdal":
            img_data = gdal.Open(raster_path)
            if not img_data:
                raise ValueError(f"无法打开图片: {raster_path}！")
        case "rasterio":
            import rasterio
            img_data = rasterio.open(raster_path)
        case "pil":
            from PIL import Image
            img_data = Image.open(raster_path)
        case 'cv2':
            import cv2
            img_data = cv2.imdecode(np.fromfile(raster_path, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
        case _:
            raise ValueError(f"不支持的backend: {backend}！")

    return img_data


def copy_data_source(src_data_source: ogr.DataSource, save_shp_path: str):
    """
    复制数据源
    :param src_data_source: 源数据源
    :param save_shp_path: 保存路径
    :return:
    """
    Path(save_shp_path).parent.mkdir(parents=True, exist_ok=True)
    shp_driver: ogr.Driver = ogr.GetDriverByName("ESRI Shapefile")
    shp_driver.CopyDataSource(src_data_source, save_shp_path)
    with open(Path(save_shp_path).with_suffix('.cpg'), 'w', encoding='utf-8') as f:
        f.write('UTF-8')
